<script setup lang="ts">
import type { AccountInfo, AccountSettlementRecords } from '@/api/types/finance'
import type { InfoItem } from '@/components/DetailCard.vue'

import { computed, ref } from 'vue'
import { getAccountById, getAccountSettlementRecordsById } from '@/api/finance'
import ApprovalActionBar from '@/components/ApprovalActionBar.vue'
import ApprovalStatusCard from '@/components/ApprovalStatusCard.vue'
import DetailCard from '@/components/DetailCard.vue'
import { useFlow } from '@/hooks/useFlow'
import { formatDate } from '@/utils/timeUtils'

// 页面配置
definePage({
  style: {
    backgroundColor: '#f5f5f5',
    navigationBarTitleText: '资金调拨详情',
    // navigationBarTextStyle: 'white',
    // navigationBarBackgroundColor: '#3b82f6',
    enablePullDownRefresh: true,
  },
})

const idValue = ref('')
const flowIdValue = ref('')
const error = ref<string | null>(null)
const transferDetail = ref<AccountSettlementRecords | null>(null)
const paymentAccountInfo = ref<AccountInfo | null>(null)
const receiveAccountInfo = ref<AccountInfo | null>(null)
const accountLoading = ref(false)

// 使用流程hook
const { currentProcess, getProcessInstance, getCurrentUserPendingTaskId, loading: flowLoading } = useFlow()

// 基本信息
const basicInfo = computed<InfoItem[]>(() => {
  if (!transferDetail.value)
    return []

  return [
    {
      label: '业务编号',
      value: transferDetail.value.bizNo || '-',
      key: 'bizNo',
    },
    {
      label: '调拨金额',
      value: transferDetail.value.transactionAmount ? transferDetail.value.transactionAmount.toFixed(2) : '0.00',
      key: 'transactionAmount',
      type: 'currency',
    },
    {
      label: '资金来源',
      value: transferDetail.value.sourceOfFunds || '-',
      key: 'sourceOfFunds',
    },
    {
      label: '款项类型',
      value: transferDetail.value.costName || '-',
      key: 'costName',
    },
    {
      label: '交易时间',
      value: transferDetail.value.transactionTime ? formatDate(transferDetail.value.transactionTime, 'datetime_short') : '-',
      key: 'transactionTime',
    },
    {
      label: '备注',
      value: transferDetail.value.remark || '-',
      key: 'remark',
      forceMultiline: true,
    },
  ]
})

// 调出账户信息
const fromAccountInfo = computed<InfoItem[]>(() => {
  if (!transferDetail.value) {
    return []
  }
  return [
    {
      label: '付款账户类型',
      value: transferDetail.value.paymentAccountType || '-',
      key: 'paymentAccountType',
    },
    {
      label: '付款账户名称',
      value: transferDetail.value.paymentAccountName || '-',
      key: 'paymentAccountName',
    },
    {
      label: '付款银行名称',
      value: transferDetail.value.paymentBankName || '-',
      key: 'paymentBankName',
    },
    {
      label: '付款账号',
      value: transferDetail.value.paymentAccountNumber || '-',
      key: 'paymentAccountNumber',
    },
    {
      label: '账户余额',
      value: paymentAccountInfo.value?.balance ? paymentAccountInfo.value.balance.toFixed(2) : '0.00',
      key: 'paymentAccountBalance',
      type: 'currency',
    },
    {
      label: '付款主体',
      value: transferDetail.value.paymentEntity || '-',
      key: 'paymentEntity',
    },
  ]
})

// 调入账户信息
const toAccountInfo = computed<InfoItem[]>(() => {
  if (!transferDetail.value)
    return []

  return [
    {
      label: '收款账户类型',
      value: transferDetail.value.receiveAccountType || '-',
      key: 'receiveAccountType',
    },
    {
      label: '收款账户名称',
      value: transferDetail.value.receiveAccountName || '-',
      key: 'receiveAccountName',
    },
    {
      label: '收款账号',
      value: transferDetail.value.receiveAccountNumber || '-',
      key: 'receiveAccountNumber',
    },
    {
      label: '账户余额',
      value: receiveAccountInfo.value?.balance ? receiveAccountInfo.value.balance.toFixed(2) : '0.00',
      key: 'receiveAccountBalance',
      type: 'currency',
    },
    {
      label: '收款银行名称',
      value: transferDetail.value.receiveBankName || '-',
      key: 'receiveBankName',
    },
    {
      label: '收款主体',
      value: transferDetail.value.receiveEntity || '-',
      key: 'receiveEntity',
    },
  ]
})

// 申请信息
const applyInfo = computed<InfoItem[]>(() => {
  if (!transferDetail.value)
    return []

  return [
    {
      label: '操作员',
      value: transferDetail.value.operator || '-',
      key: 'operator',
    },
    {
      label: '创建人',
      value: transferDetail.value.createName || '-',
      key: 'createName',
    },
    {
      label: '创建时间',
      value: transferDetail.value.createTime ? formatDate(transferDetail.value.createTime, 'datetime') : '-',
      key: 'createTime',
    },
  ]
})

// 获取账户余额信息
async function fetchAccountBalances(paymentAccountId?: string, receiveAccountId?: string) {
  // 验证输入参数
  if (!paymentAccountId && !receiveAccountId)
    return

  accountLoading.value = true

  try {
    // 并行请求账户的余额信息
    const promises = []

    if (paymentAccountId) {
      promises.push(getAccountById(paymentAccountId)
        .then((res) => {
          paymentAccountInfo.value = res.data || null
        })
        .catch((err) => {
          console.error('获取付款账户余额失败:', err)
          // 单个账户查询失败不影响其他账户查询
        }),
      )
    }

    if (receiveAccountId) {
      promises.push(getAccountById(receiveAccountId)
        .then((res) => {
          receiveAccountInfo.value = res.data || null
        })
        .catch((err) => {
          console.error('获取收款账户余额失败:', err)
          // 单个账户查询失败不影响其他账户查询
        }),
      )
    }

    // 等待所有请求完成
    await Promise.allSettled(promises)
  }
  catch (err) {
    console.error('获取账户余额失败:', err)
  }
  finally {
    accountLoading.value = false
  }
}

// 获取调拨详情
async function fetchTransferDetail() {
  try {
    flowLoading.value = true
    error.value = null

    // 重置账户信息
    paymentAccountInfo.value = null
    receiveAccountInfo.value = null

    // 先获取流程实例信息
    await getProcessInstance(idValue.value)
    // 获取当前用户待审批任务ID
    const taskId = await getCurrentUserPendingTaskId(idValue.value)
    if (taskId) {
      flowIdValue.value = taskId
    }

    // 调用真实API获取资金调拨详情
    const res = await getAccountSettlementRecordsById(currentProcess.value?.businessKey || '')
    transferDetail.value = res.data || null

    // 获取账户余额信息
    if (transferDetail.value) {
      // 使用accountId作为付款账户ID
      const paymentId = transferDetail.value.paymentAccountId || ''

      // 尝试从settlementId获取收款账户ID（如果适用）
      // 注意：这是一个假设，需要根据实际业务逻辑调整
      const receiveId = transferDetail.value.receiveAccountId || ''

      // 请求账户余额信息
      await fetchAccountBalances(paymentId, receiveId)
    }
  }
  catch (err) {
    error.value = '获取调拨详情失败'
    console.error('获取调拨详情失败:', err)
  }
  finally {
    flowLoading.value = false
  }
}

// 页面加载
onLoad((e) => {
  if (e.id) {
    idValue.value = e.id as string
  }
  if (e.flowId) {
    flowIdValue.value = e.flowId as string
  }
  fetchTransferDetail()
})

// 下拉刷新
onPullDownRefresh(async () => {
  await fetchTransferDetail()
  uni.stopPullDownRefresh()
})
</script>

<template>
  <view class="page">
    <!-- 加载状态 -->
    <view v-if="flowLoading" class="h-screen w-full flex items-center justify-center">
      <text class="ml-2 text-sm text-gray-600">加载中...</text>
    </view>

    <!-- 错误状态 -->
    <view v-else-if="error" class="h-screen w-full flex items-center justify-center">
      <text class="text-red-500">{{ error }}</text>
      <button class="ml-2" @click="fetchTransferDetail">
        重新加载
      </button>
    </view>

    <!-- 无数据状态 -->
    <view v-else-if="!transferDetail?.id && !transferDetail?.bizNo" class="h-screen w-full flex items-center justify-center">
      <text class="text-gray-500">未找到调拨信息</text>
    </view>

    <!-- 详情内容 -->
    <template v-else>
      <!-- 审批状态卡片 -->
      <ApprovalStatusCard :current-process="currentProcess" :id-value="idValue" />

      <!-- 详情内容卡片 -->
      <view class="p-4">
        <!-- 基本信息 -->
        <DetailCard
          title="调拨基本信息"
          :info-list="basicInfo"
        />

        <!-- 调出账户信息 -->
        <DetailCard
          title="调出账户信息"
          :info-list="fromAccountInfo"
        />

        <!-- 调入账户信息 -->
        <DetailCard
          title="调入账户信息"
          :info-list="toAccountInfo"
        />

        <!-- 申请信息 -->
        <DetailCard
          title="申请信息"
          :info-list="applyInfo"
        />
        <!-- 审批操作栏 -->
        <ApprovalActionBar v-if="flowIdValue && currentProcess?.status === 1" :process-id="flowIdValue" />
      </view>
    </template>
  </view>
</template>

<style scoped>
.page {
  padding-bottom: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}
</style>
